# -*- coding:utf-8 -*-
import logging
import os
import time
import traceback
import urllib
from urllib import parse
# from flask_login import unicode
import hashlib

from cffi.backend_ctypes import unicode

from settings import Config

log = logging.getLogger(__file__)


def create_md5(args):
    args = args.encode("utf8")
    md5_constructor = hashlib.md5
    return md5_constructor(args).hexdigest()


def allowed_img(content_type):
    """
    判断是否是图片文件
    :param content_type:
    :return:
    """
    return content_type in ('image/png', 'image/jpeg', 'image/jpg', 'image/gif')


def file_validate(file):
    if file['size'] < 5 * 1024:
        file['error'] = 'File is too small'
    elif file['size'] > 5 * 1024:
        file['error'] = 'File is too big'
    elif not allowed_img(file['type']):
        file['error'] = 'Filetype not allowed'
    else:
        return True
    return False


def get_file_size(file):
    file.seek(0, 2)  # Seek to the end of the file
    size = file.tell()  # Get the position of EOF
    file.seek(0)  # Reset the file position to the beginning
    return size


def make_file_name(file_name, dir=""):
    """
    文件名称
    :param file_name:
    :param dir:
    :return:
    """
    fn, ext = os.path.splitext(file_name)
    new_name = []
    time_stamp = str(time.time())
    new_name.append(time_stamp)
    new_name.append(Config.SECRET_KEY)
    new_name.append(dir)
    # 中文无法加密，需转码
    if isinstance(fn, unicode):
        fn = fn.encode('utf8')
    if isinstance(fn, bytes):
        fn = str(fn, encoding="utf-8")
    new_name.append(fn)
    new_name_string = create_md5("".join(new_name))
    return "".join([new_name_string, ext])


def upload_file(type, file, module_name, bucket=None):
    """

    :param file:
    :param module_name:
    :param bucket:
    :return:
    """
    if type == 'local':
        file_name = upload_local(file, module_name)
    elif type == "aliyun":
        file_name = upload_aliyun(bucket, file, module_name)
    else:
        file_name = ''
    return file_name


def upload_local(file, module_name):
    """
    文件上传到本地
    :param file:
    :param param_name:
    :param module_name:
    :return:
    """
    save_file_name = ""
    if file and allowed_img(file.content_type):
        logo_dir = os.path.join(Config.UPLOAD_FOLDER, module_name)
        save_file_name = make_file_name(file.filename)
        if not os.path.exists(logo_dir):
            os.mkdir(logo_dir)
        file.save(os.path.join(logo_dir, save_file_name))
        save_file_name = "http://%s/static/uploads/%s/%s" % (Config.BACKEND_DOMAIN, module_name, save_file_name)
    return save_file_name


def upload_aliyun(conn_bucket, file, module_name=''):
    """
    上传文件
    :param module_name:
    :param file:
    :param conn_bucket:
    :return:
    """
    try:
        save_name = make_file_name(file.filename, module_name)

        key = "/".join(["uploads", module_name, save_name])
        stream = file.stream.read()
        result = conn_bucket.put_object(key=key, data=stream, headers={})
        if result.status == 200:
            img_name = urllib.parse.unquote(
                result.resp.response.url.replace(Config.ALIYUN_OUTER_NET, Config.ALIYUN_INNER_NET, 1))
            log.info("imgx --------->%s" % (img_name))
            return img_name
        return ""

    except:
        print(traceback.format_exc())
        log.error(traceback.format_exc())
        return ""


def get_file_content_type(file):
    """
    获取文件类型
    :param file:
    :return:
    """
    return file.content_type


if __name__ == "__main__":
    pass
